package com.zyh.io;

import java.io.*;

/**
 * @Author zyh
 * @Date 2024/8/7 9:26
 * @Description 文件夹的拷贝
 */

public class IODemo1 {
    public static void main(String[] args) {
        File sourcesFile = new File("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day10-code\\src\\com\\zyh");
        File targetFile = new File("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day11-code\\src\\com\\zyh\\io");
        copyDir(sourcesFile,targetFile);
    }

    /*
    文件夹的复制
     */
    public static void copyDir(File sourcesFile,File targetFile)  {
        //判断是否存在
        if (!sourcesFile.exists()){
            throw new  IllegalArgumentException("源文件路径不存在");
        }
        if (!targetFile.exists()){
            targetFile.mkdirs();
        }
        //遍历源文件夹
        File[] files = sourcesFile.listFiles();
        for (File ziFile : files) {
            //判断是否为文件或文件夹
            if (ziFile.isFile()){
                copyFile(ziFile,new File(targetFile,ziFile.getName()));
            }
            else {
                copyDir(ziFile,new File(targetFile,ziFile.getName()));
            }
        }
    }

    /*
    文件的复制
     */
    public static void copyFile(File sourcesFile,File targetFile){
        //复制文件
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(sourcesFile));
            bw = new BufferedWriter(new FileWriter(targetFile));
            int len=-1;
            char[] car=new char[1024<<1];
            while ((len=br.read(car))!=-1){
                bw.write(car,0,len);
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
